package com.taptech.doufu.ui.view;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.taptech.doufu.bean.personalcenter.FlowerOption;
import com.taptech.doufu.util.FetchResourceUtil;
import com.taptech.doufu.util.GsonUtil;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.util.TextUtil;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.activity.SinaWeiboActivity;
import com.taptech.doufu.ui.adapter.TTShareAdapter;
import com.taptech.doufu.ui.activity.EasyBrowseActivity;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.bean.ProductionBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.bean.ShareBeansInfo;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.bean.personalcenter.SweepFlowerBean;
import com.taptech.doufu.services.personalcenter.QQService;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.services.PersonalNoteService;
import com.taptech.doufu.ui.activity.FlowerRankActivity;
import com.taptech.doufu.ui.adapter.HorizontalListViewAdapter;
import com.taptech.doufu.util.AnimationUtil;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.ImageManager;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.net.httputils.HttpUtil;
import com.douhuayuedu.douhua.wxapi.WXUtil;
import com.taptech.doufu.weex.notification.QLXNotificationCenter;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXTextObject;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Created by longsiyang on 16/1/8.
 */
public class FlowerDialogManager implements View.OnClickListener, HttpResponseListener {

    static private Activity mContext;
    static private FlowerDialogManager flowerManager;

    PopupWindow makeGiveFlowerPopupWindow;
    private static String mId, mObjectType, mShareUrl;
    static ProductionBean bean;

    RelativeLayout backLayout;
    private View tvSendFast;

    //献花动画
    Animation flowerAnimation;
    private com.taptech.doufu.ui.view.RoundImageView flower, flowerIngUserImg;
    private ImageView[] flower_copy = new ImageView[8];
    //献花动画的状态
    private static final int REFRESH_FLOWER_STATUS = -4;
    private static final int RESET_CLICK_FLOWER = -3;
    private static final int SEND_FLOWER_FAIL = -2;
    private static final int SEND_FLOWER_SUCCESS = -1;
    private static final int SEND_FLOWER_FAST_SUCCESS = -5;
    private static final int SEND_FLOWER_TIME = 4;
    private int flower_count = 0;
    private int count = 0;
    private int flower_img_position = 8;
    private Timer timer;
    boolean isFlowerClick = false;
    /**
     * 献花按钮是否可献花，献花完后有3秒的冷却时间
     */
    private boolean flowerClickable = true;
    int flowerSum = 0;

    //献花数量提示
    private TextView flowerStatusTips;
    //开始献花的文字提示
    private TextView startFlowerTips;
    //无人献花时的提示
    private TextView no_flower;
    //日志献花总数
    private TextView flower_sum;
    //献花列表
    private HorizontalListView flowerUserList;
    private HorizontalListViewAdapter flowerUserAdapter;
    private List<SweepFlowerBean> flowerUserListDatas;

    private String fastOptionTitle1;
    private String fastOptionTitle2;
    private List<FlowerOption> fastOption;

    // 缺豆子献花失败时的ui
    RelativeLayout getDouziLayout;
    TextView douziTextDes;
    TextView douziDesBtn, shareBtn;
    ImageView closeWindowBtn;

    static public FlowerDialogManager getInstance(Context context, ProductionBean productionBean, String shareUrl) {
        mShareUrl = shareUrl;
        return getInstance(context, productionBean);
    }

    static public FlowerDialogManager getInstance(Context context, ProductionBean productionBean) {
        mContext = (Activity) context;
        flowerManager = new FlowerDialogManager();
        bean = productionBean;
        if (bean != null) {
            mId = bean.getId();
            mObjectType = bean.getObject_type();
            if (mObjectType != null && mObjectType.equals("5")) {
                mObjectType = "18";
            }
        }

        flowerManager.initView();
        return flowerManager;
    }

    private FlowerDialogManager() {

    }

    private void initView() {
        if (makeGiveFlowerPopupWindow == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View flowerView = inflater.inflate(R.layout.popup_cp_give_flower, null);
            tvSendFast = flowerView.findViewById(R.id.tvSendFast);
            tvSendFast.setOnClickListener(this);
            backLayout = (RelativeLayout) flowerView.findViewById(R.id.back_layout_id);
            backLayout.setOnClickListener(this);
            initFlowerView(flowerView);
            douziLackDialogInitView(flowerView);
            initSharePopupWindow(flowerView);
            makeGiveFlowerPopupWindow = new PopupWindow(flowerView, ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
            makeGiveFlowerPopupWindow.setAnimationStyle(R.style.Animation_Bottom_Top);
            makeGiveFlowerPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
            makeGiveFlowerPopupWindow.setBackgroundDrawable(new BitmapDrawable());
            makeGiveFlowerPopupWindow.setFocusable(true);
            makeGiveFlowerPopupWindow.setOutsideTouchable(true);
        }
        PersonalNoteService.getInstance().loadFlowerList(this, mId, mObjectType, "");
        makeGiveFlowerPopupWindow.showAtLocation(mContext.getWindow().getDecorView(), Gravity.BOTTOM | Gravity.CENTER, 0, 0);
        makeGiveFlowerPopupWindow.update();
    }

    private void initFlowerView(View view) {
        flowerUserListDatas = new ArrayList<SweepFlowerBean>();
        flowerUserAdapter = new HorizontalListViewAdapter(mContext, flowerUserListDatas);
        //献花
        flower = (com.taptech.doufu.ui.view.RoundImageView) view.findViewById(R.id.give_flower_btn);
        view.findViewById(R.id.popu_cancel_bt).setOnClickListener(this);
        flower.setOnClickListener(this);
        flowerIngUserImg = (com.taptech.doufu.ui.view.RoundImageView) view.findViewById(R.id.flower_ing_userimg);
        if (WeMediaApplication.getInstance().isDayNightMode_Night) {
            View viweBg = view.findViewById(R.id.cp_give_flower_bg);
            viweBg.setBackgroundColor(mContext.getResources().getColor(R.color.black));
            viweBg.setAlpha(0.5f);
        }

        no_flower = (TextView) view.findViewById(R.id.no_flower);
        flowerStatusTips = (TextView) view.findViewById(R.id.flower_ing_status);
        startFlowerTips = (TextView) view.findViewById(R.id.flower_ing_tips);
        flower_sum = (TextView) view.findViewById(R.id.flower_sum);
        flower_sum.setOnClickListener(this);
        //献花列表
        flowerUserList = (HorizontalListView) view.findViewById(R.id.flower_rank_listview);
        flowerUserList.setAdapter(flowerUserAdapter);

        flowerAnimation = AnimationUtils.loadAnimation(mContext, R.anim.sweep_flower_rotate);
        LinearInterpolator lin = new LinearInterpolator();
        flowerAnimation.setInterpolator(lin);
        if (bean != null && bean.getUser() != null) {
            ImageManager.displayImage(flowerIngUserImg, bean.getUser().getIcon(), 0);
        }
        try {
            for (int i = 1; i < 9; i++) {
                Field fieldLayout = R.id.class.getDeclaredField("sweep_flower_copy_" + i);
                flower_copy[i - 1] = (ImageView) view.findViewById(Integer.parseInt(fieldLayout.get(null).toString()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View v) {
        if (sharePopupWindow != null && sharePopupWindow.isShown()) {
            sharePopupWindow.setVisibility(View.GONE);
        }
        switch (v.getId()) {
            case R.id.tvSendFast:
                if (!isFlowerClick) {
                    toastSendFastDialog();
                }
                break;
            case R.id.give_flower_btn:
                clickGiveFlowering();
                break;
            // 查看详细送花列表
            case R.id.flower_sum:
                Intent rankFlower = new Intent(mContext, FlowerRankActivity.class);
                rankFlower.putExtra(Constant.OBJECT_TYPE, mObjectType);
                rankFlower.putExtra(Constant.NOTE_ID, mId);
                mContext.startActivity(rankFlower);
                break;
            case R.id.popu_cancel_bt:
                if (makeGiveFlowerPopupWindow != null && makeGiveFlowerPopupWindow.isShowing()) {
                    makeGiveFlowerPopupWindow.dismiss();
                }
                break;
        }
    }

    private BottomSheetDialog bottomSheetDialog;

    private void toastSendFastDialog() {
        if (bottomSheetDialog == null) {
            bottomSheetDialog = new BottomSheetDialog(mContext);
            bottomSheetDialog.setContentView(R.layout.dialog_send_flower_fast);
            final FlowerOptionAdapter adapter = new FlowerOptionAdapter(mContext, fastOption);
            ListView optionList = (ListView) bottomSheetDialog.findViewById(R.id.optionList);
            optionList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    FlowerOption item = adapter.getItem(position);
                    if (item != null) {
                        /** 提交献花数量 */
                        PersonalNoteService.getInstance().giveFlowerToNote(FlowerDialogManager.this, mId, mObjectType, "", item.getId());
                        /** 刷新排名 */
                        PersonalNoteService.getInstance().loadFlowerList(FlowerDialogManager.this, mId, mObjectType, "");
                    }
                    bottomSheetDialog.cancel();
                }
            });
            optionList.setAdapter(adapter);
            View layCancel = bottomSheetDialog.findViewById(R.id.layCancel);
            TextView tvTitle = (TextView) bottomSheetDialog.findViewById(R.id.tvTitle);
            TextView tvDesc = (TextView) bottomSheetDialog.findViewById(R.id.tvDesc);
            tvTitle.setText(fastOptionTitle1);
            tvDesc.setText(fastOptionTitle2);
            layCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bottomSheetDialog.cancel();
                }
            });
        }
        bottomSheetDialog.show();
    }

    private void clickGiveFlowering() {
        if (flowerClickable) {


            // 定义计时器
            if (!isFlowerClick) {
                isFlowerClick = true;
                flower.startAnimation(flowerAnimation);
                flowerStatusTips.setVisibility(View.VISIBLE);
                flowerIngUserImg.setVisibility(View.VISIBLE);
                AlphaAnimation alpha = new AlphaAnimation(0f, 1f);
                alpha.setDuration(1000);
                alpha.setFillAfter(true);
                flowerIngUserImg.startAnimation(alpha);
                flowerStatusTips.startAnimation(alpha);
                flowerStatusTips.startAnimation(alpha);
                flower_copy[flower_img_position % 8].setVisibility(View.VISIBLE);
                // flower_sum.setText(++flower_count + "");
                ++flower_count;
                ++count;
                AnimationUtil.flowerAnimation(flower_copy[flower_img_position % 8]);
                flower_img_position++;
                timer = new Timer();

                timer.schedule(new TimerTask() {
                    int i = 0;

                    @Override
                    public void run() {
                        Message msg = Message.obtain();
                        msg.what = i;
                        i += 4;
                        flowerHandler.sendMessage(msg);
                    }
                }, 4000, 1000);
                startFlowerTips.setText("请连续戳我");

            } else {
                flower_copy[flower_img_position % 8].setVisibility(View.VISIBLE);
                // flower_sum.setText(++flower_count + "");
                ++flower_count;
                ++count;
                AnimationUtil.flowerAnimation(flower_copy[flower_img_position % 8]);
                flower_img_position++;
            }
            // startFlowerTips.setVisibility(View.INVISIBLE);

            flowerStatusTips.setText(flower_count + "");
        }
    }

    Handler flowerHandler = new Handler() {

        public void handleMessage(android.os.Message msg) {

            TTLog.d("tag", "献花状态处于=====================" + msg.what);
            if (msg.what == (SEND_FLOWER_TIME)) {
                flowerStatusTips.setText("时间到!");
                startFlowerTips.setText("");
                flowerClickable = false;
                isFlowerClick = false;
                flower.clearAnimation();

                if (timer != null) {
                    timer.cancel();
                    timer = null;
                }
                flowerHandler.sendMessageDelayed(flowerHandler.obtainMessage(REFRESH_FLOWER_STATUS), 500);

            } else if (msg.what == SEND_FLOWER_FAST_SUCCESS) {
                Toast.makeText(mContext, "献花成功", Toast.LENGTH_LONG).show();

                flower_sum.setText((flowerSum + flower_count) + ">");
                HashMap resParam = new HashMap();
                resParam.put("count", flowerSum + flower_count);
                QLXNotificationCenter.getInstance().postNotify("TFUserSendFlowerSuccess", resParam);
                flower_count = 0;
                count = 0;
                flowerHandler.sendMessageDelayed(flowerHandler.obtainMessage(RESET_CLICK_FLOWER), 4000);

            } else if (msg.what == SEND_FLOWER_SUCCESS) {
                String autor = "作者";

                DiaobaoUtil.flowerFinish(flowerStatusTips, flower_count, autor);

                SpannableString textSpan = new SpannableString("扣5个豆子");
                ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor("#f96d6d"));

                try {
                    Pattern p = Pattern.compile("5");
                    Matcher m = p.matcher("扣5个豆子");
                    while (m.find()) {
                        int start = m.start();
                        int end = m.end();
                        textSpan.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }

                } catch (PatternSyntaxException e) {
                    e.printStackTrace();
                }
                // flowerStatusTips.setText(textSpan);
                flower_sum.setText((flowerSum + flower_count) + ">");

                HashMap resParam = new HashMap();
                resParam.put("count", flowerSum + flower_count);

                QLXNotificationCenter.getInstance().postNotify("TFUserSendFlowerSuccess", resParam);

                AnimationUtil.starAlphaAnimation(flowerIngUserImg, 3000);
                AnimationUtil.starAlphaAnimation(flowerStatusTips, 3000);
                flower_count = 0;
                count = 0;
                flowerHandler.sendMessageDelayed(flowerHandler.obtainMessage(RESET_CLICK_FLOWER), 4000);

            } else if (msg.what == SEND_FLOWER_FAIL) {
                if (!TextUtils.isEmpty((String) msg.obj)) {
                    Toast.makeText(mContext, (String) msg.obj, Toast.LENGTH_LONG).show();
                    flowerStatusTips.setText((String) msg.obj);
                }
                flower_sum.setText((flowerSum + flower_count - count) + ">");
                AnimationUtil.starAlphaAnimation(flowerIngUserImg, 1000);
                AnimationUtil.starAlphaAnimation(flowerStatusTips, 1000);
                flower_count = 0;
                count = 0;
                flowerHandler.sendMessageDelayed(flowerHandler.obtainMessage(RESET_CLICK_FLOWER), 4000);

            } else if (msg.what == REFRESH_FLOWER_STATUS) {// 献花结束，刷新
                /** 提交献花数量 */
                PersonalNoteService.getInstance().giveFlowerToNote(FlowerDialogManager.this, mId, mObjectType, String.valueOf(count));
                /** 刷新排名 */
                PersonalNoteService.getInstance().loadFlowerList(FlowerDialogManager.this, mId, mObjectType, "");

            } else if (msg.what == RESET_CLICK_FLOWER) {// 恢复献花按钮
                flowerClickable = true;
                flowerStatusTips.setText("");
                // startFlowerTips.setVisibility(View.VISIBLE);
                startFlowerTips.setText("赠人菊花，手有余香");
            }

        }
    };

    @Override
    public void handleResponse(int handleType, HttpResponseObject response) {
        if (response == null) {
            return;
        }
        if (handleType == PersonalNoteService.HANDLE_TYPE_GIVE_FLOWER ||
                handleType == PersonalNoteService.HANDLE_TYPE_GIVE_FLOWER_FAST) {

            if (response.getStatus() == Constant.STATUS_SUCCESS) {
                if (handleType == PersonalNoteService.HANDLE_TYPE_GIVE_FLOWER_FAST) {
                    flowerHandler.sendEmptyMessage(SEND_FLOWER_FAST_SUCCESS);
                } else {
                    flowerHandler.sendEmptyMessage(SEND_FLOWER_SUCCESS);
                }
            } else if (response.getStatus() == 25) {
                if (response.getUser_msg() != null) {
                    getDouziLayout.setVisibility(View.VISIBLE);
                    douziTextDes.setText(response.getUser_msg());
                } else {
                    UIUtil.toastMessage(mContext, Constant.loadingFail);
                }
                Message mes = Message.obtain();
                mes.obj = "";
                mes.what = SEND_FLOWER_FAIL;
                flowerHandler.sendMessage(mes);
            } else {
                Message mes = Message.obtain();
                mes.obj = DiaobaoUtil.getErrorTips(response).trim();
                mes.what = SEND_FLOWER_FAIL;
                flowerHandler.sendMessage(mes);
            }
        } else {
            if (response.getStatus() == 0) {
                switch (handleType) {
                    case PersonalNoteService.HANDLE_TYPE_LOAD_FLOWER_LIST:
                        final JSONObject jsonObject = (JSONObject) response.getData();

                        List<SweepFlowerBean> mainList;

                        try {
                            if (jsonObject.get("list") instanceof JSONArray) {
                                mainList = new ArrayList<SweepFlowerBean>();
                                JSONArray mainArray = jsonObject.getJSONArray("list");
                                SweepFlowerBean contentBean = null;
                                for (int i = 0; i < mainArray.length(); i++) {
                                    contentBean = new SweepFlowerBean();
                                    if (mainArray.get(i) instanceof JSONObject) {
                                        contentBean.setJson(mainArray.getJSONObject(i));
                                    }
                                    mainList.add(contentBean);
                                }

                                if (mainList.size() != 0) {
                                    no_flower.setVisibility(View.GONE);
                                    flowerUserListDatas.clear();
                                    flowerUserListDatas.addAll(mainList);
                                    //flowerUserAdapter.setFlowerInfo(mainList);
                                    flowerUserAdapter.notifyDataSetChanged();
                                    try {
                                        flowerSum = Integer.valueOf(jsonObject.getString("flowerCount"));
                                        flower_sum.setText(flowerSum + ">");
                                    } catch (Exception e) {

                                    }


                                } else {
                                    no_flower.setVisibility(View.VISIBLE);
                                    flower_sum.setText("0>");
                                }
                            }

                            fastOptionTitle1 = jsonObject.getString("title1");
                            fastOptionTitle2 = jsonObject.getString("title2");
                            fastOption = GsonUtil.jsonToList(jsonObject.getJSONArray("fast_options").toString(), FlowerOption[].class);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        break;
                }

            } else {
                if (response.getUser_msg() != null) {
                    UIUtil.toastMessage(mContext, response.getUser_msg());
                } else {
                    UIUtil.toastMessage(mContext, Constant.loadingFail);
                }
            }
        }
    }

    // 缺豆子献花弹窗初始化
    private void douziLackDialogInitView(View view) {
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.jump_to_douzi_des_btn:
                        String url = "http://www.doufu.la/static/score/rule.html";
                        Intent intent = new Intent();
                        intent.setClass(mContext, EasyBrowseActivity.class);
                        intent.putExtra(Constant.URL, url);
                        intent.putExtra(Constant.TITLE, "豆子攻略");
                        mContext.startActivity(intent);
                        break;
                    case R.id.jump_to_share_btn:
                        sharePopupWindow.setVisibility(View.VISIBLE);

                        break;
                    case R.id.close_btn:
                        getDouziLayout.setVisibility(View.GONE);
                        break;
                }
            }
        };
        getDouziLayout = (RelativeLayout) view.findViewById(R.id.get_douzi_dialog_layout);
        douziTextDes = (TextView) view.findViewById(R.id.text_des_content);
        douziDesBtn = (TextView) view.findViewById(R.id.jump_to_douzi_des_btn);
        shareBtn = (TextView) view.findViewById(R.id.jump_to_share_btn);
        closeWindowBtn = (ImageView) view.findViewById(R.id.close_btn);
        douziDesBtn.setOnClickListener(onClickListener);
        shareBtn.setOnClickListener(onClickListener);
        closeWindowBtn.setOnClickListener(onClickListener);
    }


    // wx
    private IWXAPI wxAPI;
    private String shareDoufuStr = "快来豆花，你就是我失散多年的基友！【豆花App，女性向创作社区】下载戳：";
    private Button mCancel;
    private GridView mShareGridView;
    private ShareBeansInfo shareInfo = new ShareBeansInfo(ShareBeansInfo.OWN_SHARE_FLAG);
    ;
    private RelativeLayout sharePopupWindow;

    private void registerShareServices() {
        // wx
        wxAPI = WXAPIFactory.createWXAPI(mContext, Constant.WX_APP_ID, true);
        wxAPI.registerApp(Constant.WX_APP_ID);
    }


    private void initSharePopupWindow(View view) {
        registerShareServices();
        sharePopupWindow = (RelativeLayout) view.findViewById(R.id.share_window_layout);
        mShareGridView = (GridView) view.findViewById(R.id.dialog_share_layout_gv);
        mCancel = (Button) view.findViewById(R.id.dialog_share_cancel);
        mCancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                sharePopupWindow.setVisibility(View.GONE);
            }
        });
        TTShareAdapter adapter = new TTShareAdapter(mContext);
        mShareGridView.setAdapter(adapter);
        mShareGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                sharePopupWindow.setVisibility(View.GONE);
                shareInfo.setId(bean.getId());
                shareInfo.setObject_type(mObjectType);
                shareInfo.setShareUrl(mShareUrl);
                HomeMainServices.getInstance().getShareUrlRequest(shareInfo.getId(), shareInfo.getObject_type(), new HttpResponseListener() {
                    @Override
                    public void handleResponse(int handleType, HttpResponseObject response) {
                        HttpUtil.setOnHandleHttpResponListener(mContext, handleType, response, new HttpUtil.HandleHttpResponListener() {
                            @Override
                            public void handleRespon(int handleType, JSONObject data) {
                                String urlId = "";
                                try {
                                    urlId = data.getString("id");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                if (shareInfo.shareUrl.contains("?")) {
                                    shareInfo.shareUrl += ("&share_id=" + urlId);
                                } else {
                                    shareInfo.shareUrl += ("?share_id=" + urlId);
                                }

                                int share_social_type = 100;
                                switch (position) {
                                    case TTShareAdapter.SHARE_TO_SINA_WEIBO:
                                        shareToSinalWeibo();
                                        share_social_type = 101;
                                        break;

                                    case TTShareAdapter.SHARE_TO_WEIXIN:
                                        shareToWeixin();
                                        share_social_type = 102;
                                        break;

                                    case TTShareAdapter.SHARE_TO_PENGYOUQUAN:
                                        shareToPengyouquan();
                                        share_social_type = 103;
                                        break;

                   /* case TTShareAdapter.SHARE_TO_TECENT_WEIBO:
                        shareToTecentWeibo();
                        share_social_type = 104;
                        break;*/
                                    case TTShareAdapter.SHARE_TO_MESSAGE:
                                        shareToMessage();
                                        share_social_type = 105;
                                        break;

                                    case TTShareAdapter.SHARE_TO_EMAIL:
                                        shareToEmail();
                                        share_social_type = 106;
                                        break;
                                    case TTShareAdapter.SHARE_TO_SYSTEM_MORE:
                                        shareToSystemMore();
                                        break;
                                    case TTShareAdapter.SHARE_TO_TECENT_QQ:
                                        shareQQ();
                                        share_social_type = 107;
                                        break;
                                    case TTShareAdapter.SHARE_TO_TECENT_SPACE:
                                        shareQQSpace();
                                        share_social_type = 108;
                                        break;
                                    case TTShareAdapter.COPY_THE_SHARE_LINK:
                                        if (shareInfo != null && shareInfo.getShareUrl() != null) {
                                            UIUtil.toastMessage(mContext, "复制链接成功");
                                            TextUtil.copyString2Clipboard(mContext, shareInfo.getShareUrl());
                                        }
                                        break;
                                    default:
                                        break;
                                }
                                shareInfo.setSocial_type(share_social_type);
                            }
                        });
                    }
                }, shareInfo.shareUrl);

            }
        });
    }

    public static int qq_share_type = 0;

    public void shareToSinalWeibo() {
        String shareText = "";
        switch (shareInfo.getFlag()) {
            case ShareBeansInfo.OWN_SHARE_FLAG:
                shareText = shareDoufuStr + Constant.DOWN_URL_WB + " @豆花";
                break;
            case ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG:
                //			shareText=shareInfo.getTitle()+ " " +shareInfo.getDescription()+ " " +shareInfo.getShareUrl();
                shareText = shareInfo.getTitle() + " " + shareInfo.getDescription() + " " + shareChannel(shareInfo.shareUrl, Constant.ShareChannel.SinaWeibo);
                break;
            default:
                break;
        }
        shareInfo.setShartText(shareText);
        Intent intent = new Intent(mContext, SinaWeiboActivity.class);
        intent.putExtra("flag", shareInfo.getFlag());
        intent.putExtra("shareInfo", shareInfo);
        mContext.startActivityForResult(intent, 0);

    }

    public static int wxShareType;

    private void shareToWeixin() {
        Bitmap bmp = null;
        switch (shareInfo.getFlag()) {
            case ShareBeansInfo.OWN_SHARE_FLAG:
                if (bmp == null) {
                    bmp = FetchResourceUtil.fetchBitmap(mContext.getResources(), R.drawable.new_icon);
                }
                shareInfo.setShareUrl(mContext.getResources().getString(R.string.about_us_office_website_content));
                shareInfo.setTitle("豆花App，女性向创作社区");
                shareInfo.setDescription("：彩虹无罪，有爱万岁。快来豆花，你就是我失散多年的基友！");
                break;
            case ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG:
                //			shareInfo.setTitle(shareInfo.getShartText());
                shareInfo.setShareUrl(shareChannel(shareInfo.getShareUrl(), Constant.ShareChannel.Weixin));
                break;
            default:
                break;
        }
        WXWebpageObject webpageObj = new WXWebpageObject();
        webpageObj.webpageUrl = shareInfo.getShareUrl();
        WXMediaMessage msg = new WXMediaMessage();
        msg.title = shareInfo.getTitle();
        msg.mediaObject = webpageObj;
        msg.description = shareInfo.getDescription();
        if (bmp != null) {
            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, Constant.WXData.THUMB_WIDTH_SIZE, Constant.WXData.THUMB_HEIGHT_SIZE, true);
            msg.thumbData = WXUtil.bmpToByteArray(thumbBmp, true);
        }
        //		msg.description = mPaperDescription;
        WXTextObject textObject = new WXTextObject();
        textObject.text = shareInfo.getTitle();
        ;
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.scene = SendMessageToWX.Req.WXSceneSession; // for wechat friends
        wxShareType = SendMessageToWX.Req.WXSceneSession;
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        wxAPI.sendReq(req);

    }

    private void shareToPengyouquan() {

        if (wxAPI.getWXAppSupportAPI() < Constant.WXData.PENG_YOU_QUAN_MIN_VERSION_CODE) {
            Toast.makeText(mContext, R.string.info_share_pengyouquan_version_too_low, Toast.LENGTH_LONG).show();
            return;
        }
        Bitmap bmp = null;
        switch (shareInfo.getFlag()) {
            case ShareBeansInfo.OWN_SHARE_FLAG:
                bmp = FetchResourceUtil.fetchBitmap(mContext.getResources(), R.drawable.new_icon);
                shareInfo.setShareUrl(mContext.getResources().getString(R.string.about_us_office_website_content));
                shareInfo.setDescription("【有爱万岁】豆花，女性向创作社区");
                shareInfo.setTitle("豆花App，女性向创作社区");
                break;
            case ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG:
                //			shareInfo.setTitle(shareInfo.getShartText());
                shareInfo.setShareUrl(shareChannel(shareInfo.getShareUrl(), Constant.ShareChannel.pengyouquan));
                break;
            default:
                break;
        }
        WXWebpageObject webpageObj = new WXWebpageObject();
        webpageObj.webpageUrl = shareInfo.getShareUrl();

        WXMediaMessage msg = new WXMediaMessage();
        msg.title = shareInfo.getTitle();
        msg.mediaObject = webpageObj;
        msg.description = shareInfo.getDescription();
        if (bmp != null) {
            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, Constant.WXData.THUMB_WIDTH_SIZE, Constant.WXData.THUMB_HEIGHT_SIZE, true);
            msg.thumbData = WXUtil.bmpToByteArray(thumbBmp, true);
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.scene = SendMessageToWX.Req.WXSceneTimeline; // for pengyou quan
        wxShareType = SendMessageToWX.Req.WXSceneTimeline;
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        wxAPI.sendReq(req);
    }

    private void shareToMessage() {
        String smsBody = "";
        switch (shareInfo.getFlag()) {

            case ShareBeansInfo.OWN_SHARE_FLAG:
                smsBody = "您的好朋友邀请您下载【豆花，女性向创作社区】官网下载：" + Constant.DOWN_URL_DX;
                break;
            case ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG:
                //			smsBody=shareInfo.getShartText()+shareInfo.shareUrl;
                //			smsBody=shareInfo.getTitle()+": "+shareInfo.getDescription()+" "+shareInfo.shareUrl;
                smsBody = shareChannel(shareInfo.getTitle() + ": " + shareInfo.getDescription() + " " + shareInfo.shareUrl, Constant.ShareChannel.other);
                break;
        }
        Uri smsToUri = Uri.parse("smsto:");
        Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
        intent.putExtra("sms_body", smsBody);
        mContext.startActivity(intent);
    }

    private void shareToEmail() {
        String shareText = "";
        String title = "";
        switch (shareInfo.getFlag()) {

            case ShareBeansInfo.OWN_SHARE_FLAG:
                title = "我发现了一个超级合口味的应用";
                shareText = shareDoufuStr + Constant.DOWN_URL_YJ + " @豆花";
                break;
            case ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG:
                title = shareInfo.getTitle();
                //			shareText=shareInfo.getDescription()+" "+shareInfo.shareUrl;
                shareText = shareChannel(shareInfo.getDescription() + " " + shareInfo.shareUrl, Constant.ShareChannel.other);
                break;
        }

        try {
            Intent intent = new Intent(Intent.ACTION_SENDTO);
            //			intent.setType("message/rfc882");
            //设置邮件默认地址
            intent.putExtra(Intent.EXTRA_SUBJECT, title);
            intent.putExtra(Intent.EXTRA_TEXT, shareText);
            mContext.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(mContext, mContext.getString(R.string.info_email_start_failed), Toast.LENGTH_LONG).show();
        }
    }

    private void shareToSystemMore() {
        String shareText = "";
        String title = "";
        switch (shareInfo.getFlag()) {

            case ShareBeansInfo.AETICLE_SHARE_FLAG:
                shareText = mContext.getString(R.string.common_share_tag_prefix_start) + shareInfo.getArticleAuthor() + mContext.getString(R.string.common_share_tag_prefix_end) + "《" + shareInfo.getTitle() + "》 " + mContext.getString(R.string.common_share_tag_prefix_address) + shareInfo.getShareUrl() + " " + "@" + mContext.getString(R.string.app_name);
                title = mContext.getString(R.string.share_article_title);
                break;

        }
        TTLog.s("ShareTopPopupWindow === " + title + "==" + shareText);
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, title);
        intent.putExtra(Intent.EXTRA_TEXT, shareText);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(Intent.createChooser(intent, mContext.getString(R.string.share_title)));

    }

    private void shareQQSpace() {
        Bundle params = new Bundle();
        String title = null, summary = null, extStr = null;
        String shareUrl = "";
        String imgUrl = "";
        switch (shareInfo.getFlag()) {
            case ShareBeansInfo.OWN_SHARE_FLAG:
                title = "豆花，女性向创作社区";
                summary = shareDoufuStr + Constant.DOWN_URL_QQ + " @豆花";
                extStr = shareInfo.getShartText() + shareInfo.shareUrl;
                shareUrl = Constant.DOWN_URL_QQ;
                break;
            case ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG:
                title = shareInfo.getTitle();
                summary = shareInfo.getDescription();
                extStr = shareInfo.getDescription();
                //			shareUrl = shareInfo.getShareUrl();
                shareUrl = shareChannel(shareInfo.getShareUrl(), Constant.ShareChannel.qZone);
                imgUrl = shareInfo.getImagUrl();
                if (imgUrl == null || imgUrl.equals("")) {
                    imgUrl = Constant.LOGO_URL;
                }
                imgUrl = Constant.LOGO_URL;
                break;
            default:
                break;
        }
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_NO_TYPE);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, title);// 必填
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);// 选填
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareUrl);// 必填
        ArrayList<String> imgs = new ArrayList<String>();
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imgUrl);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, imgUrl);
        QQService.getInstance().shareToQZone(mContext, params, new IUiListener() {

            @Override
            public void onError(UiError arg0) {
            }

            @Override
            public void onComplete(Object arg0) {
                UIUtil.toastMessage(WeMediaApplication.applicationContext, "分享成功");
            }

            @Override
            public void onCancel() {
                //				UIUtil.toastMessage(WeMediaApplication.applicationContext, "已取消分享");
            }
        });

    }

    private void shareQQ() {
        Bundle params = new Bundle();
        String title = null, summary = null, extStr = null;
        String shareUrl = "";
        String imgUrl = "";
        switch (shareInfo.getFlag()) {
            case ShareBeansInfo.OWN_SHARE_FLAG:
                title = "豆花App，女性向创作社区";
                summary = "快来豆花，你就是我失散多年的基友！";
                extStr = shareDoufuStr + Constant.DOWN_URL_QQ + " @豆花";
                shareUrl = Constant.DOWN_URL_QQ;
                break;
            case ShareBeansInfo.ANSWER_SORCE_SHARE_FLAG:
                title = shareInfo.getTitle();
                summary = shareInfo.getDescription();
                extStr = shareInfo.getDescription();
                //			shareUrl = shareInfo.getShareUrl();
                shareUrl = shareChannel(shareInfo.getShareUrl(), Constant.ShareChannel.qq);
                imgUrl = shareInfo.getImagUrl();
                if (imgUrl == null || imgUrl.equals("")) {
                    imgUrl = Constant.LOGO_URL;
                }
                break;
            default:
                break;
        }
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);
        params.putString(QQShare.SHARE_TO_QQ_EXT_STR, extStr);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, shareUrl);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imgUrl);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "豆花");
        QQService.getInstance().shareToQQ(mContext, params, new IUiListener() {

            @Override
            public void onError(UiError arg0) {
            }

            @Override
            public void onComplete(Object arg0) {
                UIUtil.toastMessage(WeMediaApplication.applicationContext, "分享成功");
            }

            @Override
            public void onCancel() {
                //				UIUtil.toastMessage(WeMediaApplication.applicationContext, "已取消分享");
            }
        });

    }

    private String shareChannel(String shareUrl, String channel) {
        if (shareUrl.contains("?")) {
            shareUrl = shareUrl + "&channel=" + channel;
        } else {
            shareUrl = shareUrl + "?channel=" + channel;
        }
        return shareUrl;

    }


}
